import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
    Table,
    Button,
    Card,
    Row,
    Col,
    Input,
    Select,
    Divider,
    Tooltip,
    Dropdown,
    Menu,
} from 'antd';
import { DownOutlined } from '@ant-design/icons';

import { ModelType } from './model';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { Item } = Form;
const { pathname } = window.location;

interface CampusCommunityListProps extends FormComponentProps {
    dispatch: Dispatch<any>;
    loading: boolean;
    campusCommunityList: ModelType;
    dataInfo: any;
    INITINFO: any;
    checkPerm: any;
    screen: string;
    hasPath: boolean;
}

interface CampusCommunityListState {
    searchValues: any;
    pageIndex: number;
    pageSize: number;
    rowId: number;
}

@connect(
    ({
        campusCommunityList: { dataInfo },
        common: { INITINFO, checkPerm },
        global: { screen, hasPath },
        loading,
    }: any) => ({
        dataInfo,
        INITINFO,
        checkPerm,
        screen,
        hasPath,
        loading: loading.effects['campusCommunityList/fetch'],
    }),
)
class CampusCommunityList extends React.Component<CampusCommunityListProps,
CampusCommunityListState> {
    columns: any = [
        {
            title: '校园小区',
            dataIndex: 'name',
            render: (text: string, record: any) => (
                <Tooltip title={text}>
                    <div
                        className="wordOmit nameLink"
                        onClick={() => this.handleEditCampusCommunity(record.id, record.name)}
                    >
                        {text}
                    </div>
                </Tooltip>
            ),
        },
        {
            title: '场景类型',
            dataIndex: 'type',
            width: 100,
            render: (value: number) => {
                const { INITINFO: { gardenType } } = this.props;
                const typeValue = gardenType.map((item: any) => {
                    if (item.mCode === value) {
                        return item.codeName;
                    }
                    return null;
                });
                return <span>{typeValue}</span>;
            },
        },
        {
            title: '地址',
            dataIndex: 'address',
            render: (val: string) => (
                <Tooltip title={val}>
                    <div className="wordOmit">{val}</div>
                </Tooltip>
            ),
        },
        {
            title: '所属物业',
            dataIndex: 'propertyName',
            render: (val: string) => (
                <Tooltip title={val}>
                    <div className="wordOmit">{val}</div>
                </Tooltip>
            ),
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            width: 200,
        },
        {
            title: '创建人',
            dataIndex: 'createUserName',
            width: 100,
        },
        {
            title: '操作',
            dataIndex: 'id',
            width: 120,
            fixed: 'right',
            render: (id: number, record: any) => {
                const { checkPerm } = this.props;
                return (
                    <div>
                        {checkPerm.update && (
                            <span
                                className="operLink"
                                onClick={() => this.handleEditCampusCommunity(id, record.name)}
                            >
                                编辑
                            </span>
                        )}
                        {checkPerm.update && <Divider type="vertical" />}
                        <Dropdown arrow overlay={this.menu(record)}>
                            <span className="operLink">
                                更多<DownOutlined />
                            </span>
                        </Dropdown>
                    </div>
                );
            },
        },
    ];

    state: CampusCommunityListState = {
        searchValues: {},
        pageIndex: 1,
        pageSize: 20,
        rowId: 0,
    };

    static getDerivedStateFromProps(nextProps: any, preState: any) {
        const { location: { query } } = nextProps;
        const { pageIndex, pageSize, ...searchValues } = query;
        return {
            searchValues,
            pageIndex: Number(pageIndex) || 1,
            pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
        };
    }

    componentDidMount() {
        this.setFieldsValue();
        this.fetchAction('common/fetchGardenType');
        this.fetchAction('common/fetchAllProperty');
        this.fetchAction('common/fetchAreaList');
        this.verifyPermissions();

        const { dataInfo, hasPath } = this.props;
        if (dataInfo?.list?.length && !hasPath) return;
        if (hasPath) {
            const { dispatch } = this.props;
            dispatch({ type: 'global/clearPath' });
        }

        this.fetchDataValues();
    }

    componentDidUpdate(prevProps: any, prevState: any) {
        const { searchValues, pageIndex, pageSize } = this.state;
        if (!_.isEqual(searchValues, prevState.searchValues)
            || pageIndex !== prevState.pageIndex
            || pageSize !== prevState.pageSize
        ) {
            this.setFieldsValue();
            this.fetchDataValues();
        }
    }

    setFieldsValue = () => {
        // 设置表单
        const { searchValues } = this.state;
        const { form: { setFieldsValue } } = this.props;
        setFieldsValue(searchValues);
    };

    fetchDataValues = () => {
        this.fetchAction('fetch', this.getQueryParams());
    };

    getQueryParams = () => {
        const { searchValues, pageIndex, pageSize } = this.state;
        const params = {
            ...searchValues,
            pageIndex,
            pageSize,
        };
        return params;
    };

    verifyPermissions = () => {
        const addparams = {
            name: 'add',
            oper: 'add',
            resource: 'conf:conf_garden',
        };
        this.fetchAction('common/fetchCheckPerm', addparams);

        const updateparams = {
            name: 'update',
            oper: 'update',
            resource: 'conf:conf_garden',
        };
        this.fetchAction('common/fetchCheckPerm', updateparams);

        const otherparams = {
            name: 'operOther',
            oper: 'set_share_depart',
            resource: 'conf:conf_garden',
        };
        this.fetchAction('common/fetchCheckPerm', otherparams);
    };

    menu = (record: any) => {
        const { checkPerm } = this.props;
        return (
            <Menu>
                <Menu.Item
                    className="operLink"
                    onClick={() => this.handleConfArea(record.id, record.name)}
                >
                    配置区域
                </Menu.Item>
                {
                    checkPerm.operOther && (
                        <Menu.Item
                            className="operLink"
                            onClick={() => this.handleConfShare(record.id, record.name)}
                        >
                            配置共享数据部门
                        </Menu.Item>
                    )
                }
                <Menu.Item
                    className="operLink"
                    onClick={() => this.handleUpdateSmsAgentStatus(record.id, !!!record.smsAgent)}
                >
                    {record.smsAgent === 0 ? '开启' : '关闭'}短信代发功能
                </Menu.Item>
                <Menu.Item
                    className="operLink"
                    onClick={() => this.handleUpdateUserPickUpStatus(record.id, !!!record.userPickup)}
                >
                    {record.userPickup === 0 ? '开启' : '关闭'}用户自主取件功能
                </Menu.Item>
            </Menu>
        );
    };

    handleSearch = (e: React.FormEvent) => {
        e.preventDefault();
        const { form: { validateFields } } = this.props;
        validateFields((errors, values) => {
            if (!errors) {
                const query = {
                    pageIndex: 1,
                    pageSize: 20,
                    ...values,
                };

                const { dispatch } = this.props;
                addTab(dispatch, {
                    name: '校园小区',
                    url: `${pathname}?${qs.stringify(query)}`,
                    isTopMenu: true,
                });
            }
        });
    };

    handleReset = () => {
        const { form: { resetFields } } = this.props;
        resetFields();

        const { dispatch } = this.props;
        addTab(dispatch, {
            name: '校园小区',
            url: pathname,
            isTopMenu: true,
        });
    };

    /**
     * 添加校园小区
     */
    handleAddCampusCommunity = () => {
        const { dispatch } = this.props;
        addTab(dispatch, {
            name: '新建校园小区',
            url: '/basic/campusCommunity/list/add',
        });
    };

    /**
     * 编辑校园小区
     */
    handleEditCampusCommunity = (id: number, name: string) => {
        const { dispatch } = this.props;
        addTab(dispatch, {
            name: `编辑${name}`,
            url: `/basic/campusCommunity/list/edit?id=${id}`,
        });
    };

    /**
     * 配置区域
     */
    handleConfArea = (id: number, name: string) => {
        const { dispatch } = this.props;
        addTab(dispatch, {
            name: `区域${name}`,
            url: `/basic/campusCommunity/list/area?gardenId=${id}&gardenName=${name}`,
        });
    };

    /**
     * 配置共享数据
     */
    handleConfShare = (id: number, name: string) => {
        const { dispatch } = this.props;
        addTab(dispatch, {
            name: `共享${name}`,
            url: `${pathname}/department?id=${id}&gardenName=${name}`,
        });
    };

    /**
     * 短信代发功能状态更新
     */
    handleUpdateSmsAgentStatus = (id: number, status: boolean) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'campusCommunityList/updateSmsAgentStatus',
            payload: { query: this.getQueryParams(), id, smsAgent: +status },
        })
    };

    /**
     * 用户自主取件状态更新
     */
     handleUpdateUserPickUpStatus = (id: number, status: boolean) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'campusCommunityList/updateUserPickUpStatus',
            payload: { query: this.getQueryParams(), id, userPickup: +status },
        })
    };

    // 改变页码
    onSelectChange = (pageIndex: number, pageSize: number) => {
        const { searchValues } = this.state;
        const { dispatch } = this.props;
        const query = { ...searchValues, pageIndex, pageSize };
        addTab(dispatch, {
            name: '校园小区',
            url: `${pathname}?${qs.stringify(query)}`,
            isTopMenu: true,
        });
    };

    fetchAction = (typeName: string, payload = {}) => {
        const type = typeName.indexOf('common') >= 0
            ? typeName : `campusCommunityList/${typeName}`;

        const { dispatch } = this.props;
        dispatch({ type, payload });
    };

    onClickRow = ({ id }: any) => ({
        onClick: () => {
            this.setState({ rowId: id });
        },
    })

    setRowClassName = ({ id }: any) => {
        const { rowId } = this.state;
        return id === rowId ? 'clickRowStyl' : '';
    }

    render() {
        const { pageIndex, pageSize } = this.state;

        const {
            form: { getFieldDecorator },
            dataInfo,
            INITINFO: { gardenType, allPropertyList, areaList },
            checkPerm,
            screen,
            loading,
        } = this.props;

        const dataSource = dataInfo ? dataInfo.list : [];
        const pagination: object = {
            total: dataInfo ? dataInfo.count : 0,
            current: pageIndex,
            pageSize,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50', '100'],
            showTotal: () => `共${dataInfo.count || 0}条数据`,
            onChange: this.onSelectChange,
            onShowSizeChange: this.onSelectChange,
        };

        if (screen === 'sm' || screen === 'lg') {
            delete this.columns[this.columns.length - 1].fixed;
        } else if (screen === 'md') {
            this.columns[this.columns.length - 1].fixed = 'right';
        }

        return (
            <>
                <PageHeader />

                <Card className="searchForm" bordered={false}>
                    <Form className="tableListForm" onSubmit={this.handleSearch}>
                        <Row gutter={12}>
                            <Col md={6} sm={24}>
                                <Item label="校园小区" colon={false}>
                                    {getFieldDecorator('name')(
                                        <Input allowClear placeholder="请输入" />,
                                    )}
                                </Item>
                            </Col>
                            <Col md={5} sm={24}>
                                <Item label="场景类型" colon={false}>
                                    {getFieldDecorator('type')(
                                        <Select allowClear placeholder="请选择">
                                            {gardenType.map((item: any) => (
                                                <Option key={item.mCode} value={String(item.mCode)}>
                                                    {item.codeName}
                                                </Option>
                                            ))}
                                        </Select>,
                                    )}
                                </Item>
                            </Col>
                            <Col md={6} sm={24}>
                                <Item label="物业公司" colon={false}>
                                    {getFieldDecorator('propertyId')(
                                        <Select
                                            showSearch
                                            allowClear
                                            placeholder="请选择"
                                            filterOption={(input: any, option: any) => (
                                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            )}
                                        >
                                            {allPropertyList.map((item: any) => (
                                                <Option title={item.name} value={String(item.id)} key={item.id}>
                                                    {item.name}
                                                </Option>
                                            ))}
                                        </Select>,
                                    )}
                                </Item>
                            </Col>
                            <Col md={4} sm={24}>
                                <Item label="选择省份" colon={false}>
                                    {getFieldDecorator('pareaCode')(
                                        <Select allowClear placeholder="请选择">
                                            {areaList.map((item: any) => (
                                                <Option key={item.id} value={String(item.code)}>
                                                    {item.name}
                                                </Option>
                                            ))}
                                        </Select>,
                                    )}
                                </Item>
                            </Col>
                            <Col md={3} sm={24}>
                                <div className="flexFeView">
                                    <Button
                                        type="primary"
                                        htmlType="submit"
                                        className="smallButton"
                                    >
                                        查询
                                    </Button>
                                    <Button
                                        type="primary"
                                        className="addButton smallButton marginL16"
                                        onClick={this.handleReset}
                                    >
                                        重置
                                    </Button>
                                </div>
                            </Col>
                        </Row>
                    </Form>
                </Card>

                <Card className="tableList" bordered={false}>
                    {
                        checkPerm.add && (
                            <div className="tableBtns">
                                <Button
                                    type="primary"
                                    size="small"
                                    className="smallButton"
                                    onClick={this.handleAddCampusCommunity}
                                >
                                    新建校园小区
                                </Button>
                            </div>
                        )
                    }
                    <Table
                        rowKey="id"
                        tableLayout="fixed"
                        className="statementTable tableHeight60"
                        columns={this.columns}
                        dataSource={dataSource}
                        pagination={pagination}
                        loading={loading}
                        scroll={{ x: 1400 }}
                        onRow={this.onClickRow}
                        rowClassName={this.setRowClassName}
                    />
                </Card>
            </>
        );
    }
}
export default Form.create<CampusCommunityListProps>()(CampusCommunityList);
